<?php

namespace App\Http\Controllers\Api;

use App\Http\Resources\Api\Account as AccountResource;
use App\Models\User;
use Illuminate\Http\Request;

class AccountController extends Controller
{

    public function show()
    {
        $user = app('auth')->user();
        return new AccountResource($user);
    }

    public function update(Request $request)
    {
        $user = app('auth')->user();
        $inputs = $this->validate($request, [
            'nickname' => 'string|max:50',
            'avatar' => 'string',
            'gender' => 'integer',
        ]);
        $user->update($inputs);

        return new \Illuminate\Http\Resources\Json\Resource($user);
    }

    /**
     * 账号、密码登录
     *
     * @param Request $request
     * @return Account|\Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $inputs = $this->validate($request, [
            'nickname' => 'required|max:50',
            'password' => 'required|max:20',
        ]);
        // $user=User::create([
        //     'nickname' => $inputs['nickname'],
        //     'password' => app('hash')->make($inputs['password']),
        // ]);
        // $user->refreshApiToken();
        // $user->save();

        if (!$user = $this->hasValidCredentials($request)) {
            return invalidation(trans('auth.failed'));
        }
        return $user;
    }

    /**
     * 验证账号、密码是否正确，是的话，返回用户对象
     *
     * @param Request $request
     * @return bool|User
     */
    protected function hasValidCredentials(Request $request)
    {
        $inputs = $request->only('nickname', 'password');
        $user = User::where('nickname', $inputs['nickname'])->first();

        if (!is_null($user) && app('hash')->check($inputs['password'], $user->getAuthPassword())) {
            return $user;
        }

        return false;
    }
}
